﻿# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.db import models
from django.core.urlresolvers import reverse
from Colaboradores.models import Colaborador
from Scope.thumbs import ImageWithThumbsField
from Scope.models import BaseNoticia

def content_image_name(instance, filename):
    return '/'.join(['arquivosblog', str(instance.nomeBlog.slugdoblog), filename])

class Blog(models.Model):
    ativo = models.BooleanField(default=True)
    nome = models.CharField(max_length=25, unique=True)
    nomeColaborador = models.ForeignKey(Colaborador, verbose_name='Colaborador')
    igreja = models.CharField(max_length=50, blank=True, null=True)
    email = models.CharField('Email do Blog', max_length=50)
    descricao = models.CharField(max_length=200, blank=True, null=True, help_text='Adicione uma descrição objetiva. Ela será mostrada quando seu blog for pesquisado no Google')
    imagem = ImageWithThumbsField('Imagem Destaque', upload_to='arquivos/blogs/', sizes=((800,600),(180,123)))
    slugdoblog = models.SlugField(max_length=255, blank=True, unique=True)
    cliques = models.IntegerField('Cliques', default=0, editable=False)
    datacriacao = models.DateTimeField(auto_now_add=True)
    dataedicao = models.DateTimeField(auto_now=True)
    autor = models.ForeignKey(User, blank=True, null=True)
    def __unicode__(self):
        return self.nome
    def get_absolute_url(self):
        return reverse('Scope.views.blog', kwargs={'slugdoblog': self.slugdoblog})
    class Meta:
        verbose_name = 'Blog'
        verbose_name_plural = 'Blogs'

class NoticiaBlog(BaseNoticia):
    subtitulo = models.CharField(max_length=200)
    imagem = ImageWithThumbsField('Imagem Destaque', upload_to=content_image_name, sizes=((800,600),(300,225)), blank=True, null=True)
    slugnoticiablog = models.SlugField(max_length=150, blank=True, unique=True)
    nomeBlog = models.ForeignKey(Blog, verbose_name='Blog')
    class Meta:
        verbose_name = 'notícia no blog'
        verbose_name_plural = 'Adicionar notícias no blog'
    def save_model(self, request, obj, form, change):
        if getattr(obj, 'added_by', None) is None:
            obj.autor = request.user
        obj.last_modified_by = request.user
        obj.save()
    def queryset(self, request):
        buscauser = super(NoticiaBlog, self).queryset(request)
        if request.user.is_superuser:
            return buscauser
        return buscauser.filter(autor=request.user)
    def __unicode__(self):
        return self.titulo
    def get_absolute_url(self):
        return reverse('Scope.views.blognoticia', kwargs={'nomeblog': self.nomeBlog.slugdoblog, 'slugnoticiablog': self.slugnoticiablog})

# SIGNALS
from django.db.models import signals
from django.template.defaultfilters import slugify

def blog_pre_save(signal, instance, sender, **kwargs):
    """
    Estamos gerando uma nova slug para evitar duplicidade
    """
    if not instance.slugdoblog:
        slug = slugify(instance.nome)
        novaslug = slug
        contador = 0

        while  Blog.objects.filter(slugdoblog = novaslug).exclude(id=instance.id).count() > 0:
            contador += 1
            novaslug = '%s-%d'%(slug, contador)
        instance.slugdoblog = novaslug
signals.pre_save.connect(blog_pre_save, sender=Blog)

def noticiablog_pre_save(signal, instance, sender, **kwargs):
    """
    Estamos gerando uma nova slug para evitar duplicidade
    """
    if not instance.slugnoticiablog:
        slug = slugify(instance.titulo)
        novaslug = slug
        contador = 0

        while  NoticiaBlog.objects.filter(slugnoticiablog = novaslug).exclude(id=instance.id).count() > 0:
            contador += 1
            novaslug = '%s-%d'%(slug, contador)
        instance.slugnoticiablog = novaslug
signals.pre_save.connect(noticiablog_pre_save, sender=NoticiaBlog)